PepSim.define('PepSim.List', {

	// first: undefined,

	// last: undefined,
	
	init: function () {
	},
	
	/*
	 * Insert at the end
	*/
	
	append: function (o) {
		var elem = {
			value: o,
			prior: null,
			next: null
		};
		if (!this.first) {
			this.first = elem;
			this.last = elem;
		} else {
			this.last.next = elem;
			elem.prior = this.last;
			this.last = elem;
		}
		
		this.checkList();
		return elem;
	},
	
	/*
	 * Remove a node
	*/
	removeNode: function (node) {
		if (!node) {
			throw Error('removeNode: node required');
		}
		
		if (node === this.first && node === this.last) {
			this.first = undefined;
			this.last = undefined;				
		} else if (node === this.first) {
			this.first = node.next;
			this.first.prior = undefined;
		} else if (node === this.last) {
			this.last = node.prior;
			this.last.next = undefined;
		} else {
			node.prior.next = node.next;
			node.next.prior = node.prior;
		}

		this.checkList();
	},
	
	checkList : function () {
		if (this.first && this.first.prior) {
			throw Error('Prior of the first element must be undefined');
		}
		if (this.last && this.last.next) {
			throw Error('Next of the last element must be undefined');
		}

	},
		
	/*
	 * Itertate throught all nodes
	*/
	
	foreach : function (callback, scope) {
		this.checkList();
		var elem = this.first,
			nextElem;
		while (elem) {
			nextElem = elem.next;
			if (!elem.value.phantom) {
				callback.call(scope, elem.value);
			} else {
				this.removeNode(elem);
			}
			elem = nextElem;
		}
	}

});